'''
Created on 23 fevr. 2011

@author: wp803469

 marche pas, j'ai utilisé les fichiers du prof directement



'''




import alsaaudio, time, audioop, struct
from math import sin,pi

def biip():
    # Channel 1
    frec1=200    #Frequency
    vol1=1        #Volume
    
    #Channel 2    
    frec2=323     #Frequency
    vol2=1        #Volume
    
    #Very basic choice of parameters
    rate = 44100
    period = 44100
    channels = 2
    
    # device initialization
    out = alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card='default')
    
    # parameters
    out.setchannels(channels)
    out.setrate(rate)
    out.setformat(alsaaudio.PCM_FORMAT_S32_LE)
    
    out.setperiodsize(period)
    
    # a list with the sinusoidal signals is built
    maxAmp = pow(2,31) - 1
    
    list = []
    i=period
    while(i>0):
        list.append(maxAmp*vol1*sin(frec1*float(i)/rate*2*pi))
        list.append(maxAmp*vol2*sin(frec2*float(i)/rate*2*pi))
        i-=1
    
    # and the list is writen over and over again. Just kill the process to stop.
    s=struct.pack('<'+channels*period*'l',*list)
    #while(1):
    #    out.write(s)
    out.write(s)


'''
    initialisation --------------------------------------
'''
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE, alsaaudio.PCM_NONBLOCK)
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(160)


'''
    on ecoute -----------------------------------------
'''
while True:
    # Read data from device
    l,data = inp.read()
    if l:    
        print audioop.max(data, 2)
        # Return the maximum of the absolute value of all samples in a fragment.
        if audioop.max(data, 2) > 2000:
            print "totooooooooo"
            biip()
    time.sleep(.05)
    
    
    
    
